require('dotenv').config();

// 检查必要的环境变量
const requiredEnvVars = [
  'PORT',
  'MONGODB_USERNAME',
  'MONGODB_PASSWORD',
  'MONGODB_HOST',
  'MONGODB_PORT',
  'MONGODB_DATABASE',
  'JWT_SECRET',
  'SESSION_SECRET'
];

const missingEnvVars = requiredEnvVars.filter(varName => !process.env[varName]);
if (missingEnvVars.length > 0) {
  console.error('缺少必要的环境变量:', missingEnvVars.join(', '));
  process.exit(1);
}

const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const { koaSwagger } = require('koa2-swagger-ui');
const swaggerSpec = require('./config/swagger');
const connectDB = require('./config/db');
const registerRoutes = require('./routes/index');
const serve = require('koa-static');
const path = require('path');
const session = require('koa-session');
const koaBody = require('koa-body');
const fs = require('fs');

// 连接数据库
connectDB();

const app = new Koa();
const port = process.env.PORT || 3000;

// 使用中间件
// app.use(bodyParser());

// 使用 koa-body 中间件，支持文件上传
app.use(koaBody({
    multipart: true,
    formidable: {
        maxFileSize: 200 * 1024 * 1024,    // 设置上传文件大小限制为 200MB
        keepExtensions: true,              // 保持文件扩展名
        multiples: true,                   // 支持多文件上传
        uploadDir: path.join(__dirname, '../uploads'),  // 设置上传目录
        onFileBegin: (name, file) => {
            // 确保上传目录存在
            const uploadDir = path.join(__dirname, '../uploads');
            if (!fs.existsSync(uploadDir)) {
                fs.mkdirSync(uploadDir, { recursive: true });
            }
        }
    }
}));

// 配置session
app.keys = [process.env.SESSION_SECRET || 'your-session-secret'];
const SESSION_CONFIG = {
  key: 'koa.sess',
  maxAge: 86400000,
  autoCommit: true,
  overwrite: true,
  httpOnly: true,
  signed: true,
  rolling: false,
  renew: false,
};

app.use(session(SESSION_CONFIG, app));

// 添加 swagger.json 路由
app.use(async (ctx, next) => {
    if (ctx.path === '/swagger.json') {
        ctx.type = 'application/json';
        ctx.body = swaggerSpec;
    } else {
        await next();
    }
});

// 配置swagger-ui
app.use(
  koaSwagger({
    routePrefix: '/api-docs',
    swaggerOptions: {
      url: '/swagger.json',
    },
  })
);

// 添加静态文件服务
app.use(serve(path.join(__dirname, 'public')));

// 注册路由
console.log('\n🚀 开始注册路由...');
registerRoutes(app);
console.log('✨ 路由注册完成\n');

// 全局错误处理
app.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    console.error('服务器错误:', err);
    ctx.status = err.status || 500;
    ctx.body = {
      message: err.message || '服务器内部错误'
    };
  }
});

// 启动服务器
app.listen(port, () => {
  console.log('\n=================================');
  console.log(`��� 服务器已启动:`);
  console.log(`📡 API 地址: http://localhost:${port}`);
  console.log(`📚 Swagger文档: http://localhost:${port}/api-docs`);
  console.log('=================================\n');
}); 